;(function(){
  'use strict';
  angular.module('controllers.resourcesWatchData.dbInfoView',[])
   .controller('dbResInfoCtrl',dbResInfoCtrl)
   .controller('dbResUsageCtrl',dbResUsageCtrl);

  function dbResInfoCtrl($scope,DBResource,DbInfoViewServer,CoreService,$cookies,$state){
    $scope.dbResInfo = {};
    $scope.toggle = {
      isFolded:true
    };
    $scope.selector = {
      moduleCode:DBResource
    };
    $scope.pageObj = {
      currentPage : 1,
      pageSize : '10'
    };
    $scope.dbInfoQuery = function(){
      var param;
      if($scope.toggle.isFolded){
        param = setParam();
        DbInfoViewServer.dbInfoQuery(param,function(res){
          if(res.state!=='10000' || is.not.array(res.data) || res.data.length === 0){
            CoreService.dialog(res.state);
            return;
          }
          $scope.pageObj.param = param;
          $scope.pageObj.param.page = {
            currentPage : 1,pageSize : '10'
          };
          $scope.pageObj.totalCount = res.data.length;
          setSeries(res.data,$scope.pageObj.currentPage,$scope.pageObj.pageSize);
          $scope.toggle.isFolded = !$scope.toggle.isFolded;
          $scope.isQuery = true;
        });
      }else{
        $scope.toggle.isFolded = !$scope.toggle.isFolded;
      }
    };
    $scope.pageSizeChange = function(size){
      $scope.pageObj.pageSize = size;
    };

    $scope.turnToPage = function(param){
      var tempParam = {
        moduleCode : param.moduleCode
      };
      DbInfoViewServer.dbInfoQuery(tempParam,function(res){
        if(res.state!=='10000' || is.not.array(res.data) || res.data.length === 0){
          CoreService.dialog(res.state);
          return;
        }
        $scope.pageObj.totalCount = res.data.length;
        setSeries(res.data,param.page.currentPage,param.page.pageSize);
      });
    }
    
    $scope.getDBUsage = function(item){
      $cookies.putObject('database',item);
      $state.go('sas.resourcesWatchData.dbUsageDetail');
    };

    function setSeries(data,currentPage,pageSize){
      var begin = (Number(currentPage)-1)*Number(pageSize);
      var end = Number(currentPage)*Number(pageSize);
      $scope.series = [];
      for(;begin < end && begin < data.length;begin++){
        $scope.series.push(data[begin]);
      }
    }

    function setParam(){
      var tempParam = {
        moduleCode : ''
      };
      if($scope.dbResInfo.moduleCode){
        tempParam.moduleCode = $scope.dbResInfo.moduleCode.moduleCode;
      }
      return tempParam;
    }
  }

  dbResInfoCtrl.$inject = ['$scope','DBResource','DbInfoViewServer','CoreService','$cookies','$state'];

  function dbResUsageCtrl($scope,COREDATA,DbInfoViewServer,CoreService,$cookies,$timeout){
    var now = new Date();
    var charts = {};
    var options = {};

    $scope.toggle = {
      isFolded:true
    };
    $scope.databaseName = $cookies.getObject('database').databaseName;
    $scope.dbResUsage = {
      quarter:{}
    };
    $scope.selector = {
      timeType:[{
          timeTypeCode: '1',
          timeTypeName: '日'
        }, {
          timeTypeCode: '3',
          timeTypeName: '月'
        }]
    };
    $scope.date = initDate('1');

    $scope.$watch('date.startTime',function(n,o){
      if(n === o || n === null || n === undefined) return;
      if($scope.date.startTime >= $scope.date.endTime) return;
      if($scope.dbResUsage.timeType && $scope.dbResUsage.timeType.timeTypeCode === '3'){
        $scope.dbResUsageForm.monthEndTime.$setValidity('time-diff',true);
        $scope.dbResUsageForm.monthStartTime.$setValidity('time-diff',true);
        $scope.dbResUsageForm.monthEndTime.$setUntouched();
        $scope.dbResUsageForm.monthStartTime.$setUntouched();
        if(new Date(n.getTime()).setMonth(n.getMonth()+3) < $scope.date.endTime.getTime()){
          $scope.dbResUsageForm.monthStartTime.$setValidity('time-diff',false);
        }
      }else{
        $scope.dbResUsageForm.dateStartTime.$setValidity('time-diff',true);
        $scope.dbResUsageForm.dateEndTime.$setValidity('time-diff',true);
        $scope.dbResUsageForm.dateEndTime.$setUntouched();
        $scope.dbResUsageForm.dateStartTime.$setUntouched();
        if(new Date(n.getTime()).setDate(n.getDate()+3) < $scope.date.endTime.getTime()){
          $scope.dbResUsageForm.dateStartTime.$setValidity('time-diff',false);
        }
      }   
    },true);

    $scope.$watch('date.endTime',function(n,o){
      if(n === o || n === null || n === undefined) return;
      if($scope.date.startTime >= $scope.date.endTime) return;
      if($scope.dbResUsage.timeType && $scope.dbResUsage.timeType.timeTypeCode === '3'){
        $scope.dbResUsageForm.monthEndTime.$setValidity('time-diff',true);
        $scope.dbResUsageForm.monthStartTime.$setValidity('time-diff',true);
        $scope.dbResUsageForm.monthEndTime.$setUntouched();
        $scope.dbResUsageForm.monthStartTime.$setUntouched();
        if(new Date(n.getTime()).setMonth(n.getMonth()-3) > $scope.date.startTime.getTime()){
          $scope.dbResUsageForm.monthEndTime.$setValidity('time-diff',false);
        }
      }else{
        $scope.dbResUsageForm.dateStartTime.$setValidity('time-diff',true);
        $scope.dbResUsageForm.dateEndTime.$setValidity('time-diff',true);
        $scope.dbResUsageForm.dateEndTime.$setUntouched();
        $scope.dbResUsageForm.dateStartTime.$setUntouched();
        if(new Date(n.getTime()).setDate(n.getDate()-3) > $scope.date.startTime.getTime()){
          $scope.dbResUsageForm.dateEndTime.$setValidity('time-diff',false);
        }
      }  
    },true);

    $scope.formatArr = [
      undefined,'yyyy-MM-dd',undefined,'yyyy-MM-01','yyyy-01-01','yyyy-01-01'
    ];

    $scope.dbResUsageQuery = function(){
      var param = {};
      if($scope.toggle.isFolded){
        param = setParam();
        DbInfoViewServer.dbUsageDetailQuery(param,function(res){
          if(res.state !== '10000' || is.not.array(res.data) || res.data.length === 0){
            CoreService.dialog(res.state);
            return;
          }
          $scope.series = res.data;
          $timeout(function(){setCharts(res.data,param);},0);
        });
      }else{
        $scope.toggle.isFolded = !$scope.toggle.isFolded;
      }
    };

    function setParam(){
      var param = {};
      if($scope.dbResUsage.timeType){
        param.timeType = $scope.dbResUsage.timeType.timeTypeCode;
        var format = $scope.formatArr[$scope.dbResUsage.timeType.timeTypeCode];
        switch($scope.dbResUsage.timeType.timeTypeCode){
          case '4':
            param.startTime = $scope.dbResUsage.quarter.startTime.substr(0,4)+'-01-01';
            param.endTime = $scope.dbResUsage.quarter.endTime.substr(0,4)+'-01-01';
            param.startQuarter = $scope.dbResUsage.quarter.startTime.substr(4,1);
            param.endQuarter = $scope.dbResUsage.quarter.endTime.substr(4,1);
            break;
          case '5':
            param.startTime = $scope.date.startTime+'-01-01';
            param.endTime = $scope.date.endTime+'-01-01';
            break;
          default :
            param.startTime = CoreService.dateFormat($scope.date.startTime,format);
            param.endTime = CoreService.dateFormat($scope.date.endTime,format);
        }
      }else{
        param.timeType = $scope.selector.timeType[0].timeTypeCode;
        param.startTime = CoreService.dateFormat($scope.date.startTime,'yyyy-MM-dd');
        param.endTime = CoreService.dateFormat($scope.date.endTime,'yyyy-MM-dd');
      }
      param.moduleCode = $cookies.getObject('database').moduleCode;
      return param;
    }

    function setCharts(resData,param){
      angular.forEach(resData,function(item,index){
         charts[index] = echarts.init(document.getElementById('dbResUsageChart'+index));
         options[index] = progressData(item,param);
         charts[index].setOption(options[index]);
      });
      $scope.toggle.isFolded = !$scope.toggle.isFolded;
      $scope.isQuery = true;
    }

    function progressData(data,param){
      var title = '';
      var seriesData = [{
        name:'查询',data:[]
      },{
        name:'更新',data:[]
      },{
        name:'插入',data:[]
      }];
      var xAxisData = [];
      var option = {};
      var timeDiff = getTimeDiff(param);
      var i = 0;
      var beginTime = new Date(param.startTime);
      var year = beginTime.getFullYear(),
          month = beginTime.getMonth(),
          day = beginTime.getDate();

      title = data.databaseIp+($scope.databaseName||'')+'数据库资源使用情况';
      for(;i<timeDiff;i++){
        xAxisData.push(CoreService.dateFormat(new Date(year,month,day+i),'yyyy-MM-dd'));
        seriesData[0].data.push((Math.random()*2.5+0.5));
        seriesData[1].data.push((Math.random()*0.9+0.1));
        seriesData[2].data.push((Math.random()*0.9+0.1));
      }
      option = new ChartOpt(title,seriesData,xAxisData);
      return option;
    }
    
    function getTimeDiff(param){
      var timeDiff;
      timeDiff = new Date(param.endTime).getTime() - new Date(param.startTime).getTime();
      return (timeDiff / 86400000);
    }

    function ChartOpt(title,seriesData,xAxisData){
      this.title = {
        text: title,
        x:'center'
      };
      this.legend = {
        data:['查询','更新','插入'],
        x:'right'
      };
      this.xAxis = [
        {
          type : 'category',
          boundaryGap : true,
          data : xAxisData
        }
      ];
      this.animation = false;
      this.yAxis = [
        {
          type : 'value',
          name : '(时间)秒'
        }
      ];
      this.series = [
        {
          name:seriesData[0].name,
          type:'line',
          data:seriesData[0].data,
          smooth:true,
          symbolSize:1
        },
        {
          name:seriesData[1].name,
          type:'line',
          data:seriesData[1].data,
          smooth:true,
          symbolSize:1
        },
        {
          name:seriesData[2].name,
          type:'line',
          data:seriesData[2].data,
          smooth:true,
          symbolSize:1
        },
      ];  
    }

    $scope.$watch('dbResUsage.timeType',function(newValue,oldValue){
      if(newValue === oldValue){
        return;
      }
      $scope.date = initDate($scope.dbResUsage.timeType.timeTypeCode);
    },true);
    
    $scope.$on('formInvalid',function(eo,flag){
      $scope.quarterInvalid = flag;
    });

    function initDate(timeType){
      var date = {};
      var year = now.getFullYear();
      var month = now.getMonth();
      var day = now.getDate()-1;
      switch(timeType){
        case '3':
          date.startTime = new Date(year,month-1);
          date.endTime = new Date(year,month);
          break;
        case '5':
          date.startTime = year;
          date.endTime = year;
          break;
        default:
          date.startTime = new Date(year,month,day);
          date.endTime = new Date(year,month,day+1);
      }
      return date;
    }
  }

  dbResUsageCtrl.$inject = ['$scope','COREDATA','DbInfoViewServer','CoreService','$cookies','$timeout'];
})();